/*++

Copyright (c) 2007  Microsoft Corporation 

Filename: 

    FrmConfig.cs

Abstract: 

    Form to configure Rack Server Virtualization pre-requisites
     
--*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UtilityManager;
using Microsoft.Win32;
using System.Data.SqlClient;
using DataManager;
using System.Reflection;
using Microsoft.EnterpriseManagement;
using System.Security;
using System.Globalization;

namespace RackServerManager
{
    public partial class FrmConfig : Form
    {     

        #region Constructor
        public FrmConfig()
        {
            InitializeComponent();
            this.btnCancel.Text = Global.GetResourceString("CancelButton_Text");
            this.btnOK.Text = Global.GetResourceString("OKButton_Text");
            this.lblDesc.Text = Global.GetResourceString("ConfigDesc_Text");
            this.lblHeader.Text = Global.GetResourceString("ConfigHeader_Text");
            this.tbPageData.Text = Global.GetResourceString("ConfigTab1_Text");
            this.lblSCOMRoot.Text = Global.GetResourceString("ConfigSCOMRoot_Label");
            //this.lblSCOMReport.Text = Global.GetResourceString("ConfigSCOMRoot_Label");
            this.lblNoOfServers.Text = Global.GetResourceString("ConfigServersNo_Label");
            this.lblCpuThreshold.Text = Global.GetResourceString("ConfigThreshold_Label");
            this.rbCPUCurrent.Text = Global.GetResourceString("ConfigCPUCurrent_Radio");
            this.rbCPUDuration.Text = Global.GetResourceString("ConfigCPUDuration_Radio");
            this.tbPageLogin.Text = Global.GetResourceString("ConfigTab2_Text");
            this.lblUsername.Text = Global.GetResourceString("ConfigUser_Label");
            this.lblPassword.Text = Global.GetResourceString("ConfigPass_Label");
            this.rbUsername.Text = Global.GetResourceString("ConfigUser_Radio");
            this.rbWindows.Text = Global.GetResourceString("ConfigWindows_Radio");
            this.Text = Global.GetResourceString("ConfigForm_Text");
            //this.lblAverageCPU.Text = Global.GetResourceString("CPUAverageText");
            //this.lblDays.Text = Global.GetResourceString("CPUDaysText");
           // this.lblHours.Text = Global.GetResourceString("CPUHoursText");
            //this.lblSCOMDataBase.Text = Global.GetResourceString("ConfigSCOMDataBase_Label");
            //this.lblReportingDatabase.Text = Global.GetResourceString("ConfigSCOMReportDB_Label");
            this.groupBoxManagementServer.Text = Global.GetResourceString("RootManagementServer");
            //this.groupBoxReportingServer.Text = Global.GetResourceString("ReportingServer");
            this.txtBoxSCOMRoot.Text=Global.ServerName;
           //this.txtBoxSCOMReport.Text=Global.ReportServerName;
            //this.txtBoxReportDatabase.Text=Global.OpsReportingDBName;
            //this.txtBoxSCOMDatabaseName.Text=Global.OpsDBName;
            this.txtBoxUsername.Text=Global.UserName;
            this.cpuThresholdUpDwn.Value = (Decimal) Global.CpuUsageThreshold;
            this.maxServersUpDwn.Value= (Decimal) Global.MaxServerConsolidate;
        }
        #endregion

        #region Events
        private void rbCPUDuration_CheckedChanged(object sender, EventArgs e)
        {
            if (rbCPUDuration.Checked == true)
            {
                panelOpsServer.Enabled = true;
                //panelCPUAverage.Enabled = true;
            }
            else
            {
                errorProviderRoot.Clear();
               
               // errorProviderDBName.Clear();
                panelOpsServer.Enabled = false;
                //panelCPUAverage.Enabled = false;
                
            }
        }            

        private void btnOK_Click(object sender, EventArgs e)
        {
            bool rootSvrName = true;
           
            bool userName = true;
            bool userException = false;
            bool scomException = false;
            string errorMsg = string.Empty;

            //Clear error provider message.
            errorProviderRoot.Clear();
          
            errorProviderUserName.Clear();
            errorProviderPswd.Clear();
           
            // Save the changes made by the user for CPU Threshold and Maximum no. of servers to consolidate
            Global.CpuUsageThreshold = Convert.ToInt32(cpuThresholdUpDwn.Value);
            Global.MaxServerConsolidate = Convert.ToInt32(maxServersUpDwn.Value);

            ManagementGroup mg = null;
            
            try
            {
                #region Validate Credentials Tab page
                if (rbUsername.Checked == true)
                {
                    if (String.IsNullOrEmpty(txtBoxUsername.Text))
                    {
                        userName = false;
                        userException = true;
                        throw new RackException(Global.GetResourceString("ConfigForm_UserName"));
                    }
                    else if (String.IsNullOrEmpty(txtBoxPassword.Text))
                    {
                        userException = true;
                        throw new RackException(Global.GetResourceString("ConfigForm_Password"));
                    }
                    Global.WindowsAuthentication = false;
                    Global.UserCredentials = true;
                    Global.UserName = txtBoxUsername.Text;
                    Global.Password = txtBoxPassword.Text;
                }
                else
                {
                    Global.WindowsAuthentication = true;
                    Global.UserCredentials = false;
                }
                #endregion

                #region Validate CPU Utilization Tab page
                if (!rbCPUCurrent.Checked)
                {
                    this.FindForm().Cursor = Cursors.WaitCursor;

                    // Check if SCOM Root /Reporting Server is not blank
                    if (String.IsNullOrEmpty(txtBoxSCOMRoot.Text))
                    {
                        rootSvrName = false;
                        scomException = true;
                        throw new RackException(Global.GetResourceString("SCOMRoot_Blank_Text"));
                    }
                    
                    
                    Global.ServerName = txtBoxSCOMRoot.Text;
                   
                    //Check whether the specified server name is valid or not.
                    

                    if (Global.UserCredentials)
                    {
                        SecureString password = new SecureString();
                        for (int i = 0; i < Global.Password.Length; i++)
                        {
                            password.AppendChar(Convert.ToChar(Global.Password.Substring(i, 1),CultureInfo.CurrentCulture));
                        }

                        ManagementGroupConnectionSettings mgSettings =
                            new ManagementGroupConnectionSettings(Global.ServerName);
                        mgSettings.UserName =Global.UserName ;
                        mgSettings.Password = password;
                        mg = ManagementGroup.Connect(mgSettings);
                    }
                    else
                        mg = ManagementGroup.Connect(Global.ServerName);

                   if (!mg.IsConnected)
                   {
                     userException = true;

                            // SDK Service not started
                     throw new RackException(String.Format(CultureInfo.CurrentCulture,Global.GetResourceString("SDK_Error")
                                , System.Environment.UserName
                                , Global.ServerName));
                   }

                   if (errorMsg.Length != 0)
                   {
                       scomException = true;
                       throw new RackException(errorMsg);
                   }
                   else
                   {
                       // Validations Done. Save the changes made by user for further use.
                       Global.DTOption = Global.DataOption.Scom;
                       this.Close();
                   }

                }
                else
                {
                    // Validations Done. Save the changes made by user for fourther use.
                    Global.DTOption = Global.DataOption.Wmi;
                    this.Close();
                }
                #endregion
            }
            catch (Microsoft.EnterpriseManagement.Common.ServerDisconnectedException)
            {
                if (Global.UserCredentials)
                {
                    errorProviderRoot.SetError(txtBoxSCOMRoot, String.Format(CultureInfo.CurrentCulture, Global.GetResourceString("UnauthorizedAccess")
                                     , Global.UserName));
                }
                else
                {
                    errorProviderRoot.SetError(txtBoxSCOMRoot, String.Format(CultureInfo.CurrentCulture, Global.GetResourceString("UnauthorizedAccess")
                                     , System.Environment.UserDomainName + "\\" + System.Environment.UserName));
                }
            }
            catch (Microsoft.EnterpriseManagement.Common.ServiceNotRunningException ex)
            {
                errorProviderRoot.SetError(txtBoxSCOMRoot, ex.Message);
            }
            catch (Microsoft.EnterpriseManagement.Common.UnauthorizedAccessMonitoringException ex)
            {
                errorProviderRoot.SetError(txtBoxSCOMRoot, ex.Message);
               
            }
            catch (RackException ex)
            {
                if (scomException)
                {
                    // SCOM exception display error messages to user
                    scomException = false;
                    if (rootSvrName == false)
                    {
                        errorProviderRoot.SetError(txtBoxSCOMRoot, ex.Message);
                    }
                   
                    else
                    {
                        errorProviderRoot.SetError(txtBoxSCOMRoot, ex.Message);
                    }
                }
               
                else if (userException)
                {
                    // Credentials exception to display error messages to user
                    userException = false;
                    if (userName == false)
                    {
                        errorProviderUserName.SetError(txtBoxUsername, ex.Message);
                    }
                    else
                    {
                        errorProviderPswd.SetError(txtBoxPassword, ex.Message);
                    }
                }
                else
                {
                    // To catch and display exceptions from sub functions
                    RackException.HandleExceptions(Global.GetResourceString("Exception_MsgBox_Caption"),
                                Global.GetResourceString("Exception_UsrMsg"), ex.InnerException);

                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains(Global.GetResourceString("Unknown_Host")))
                {
                    errorProviderRoot.SetError(txtBoxSCOMRoot, ex.Message);
                }
                else
                {
                    // To catch and display exceptions from current functions
                    RackException.HandleExceptions(Global.GetResourceString("Exception_MsgBox_Caption"),
                                Global.GetResourceString("Exception_UsrMsg"), ex);
                }

            }
            finally
            {
                mg = null;
                this.FindForm().Focus();
                this.FindForm().Cursor = Cursors.Default;
            }

        }

        private void rbWindows_CheckedChanged(object sender, EventArgs e)
        {
            if (rbUsername.Checked == true)
            {
                panelCredentials.Enabled = true;
            }
            else
            {
                panelCredentials.Enabled = false;
            }
        }

        private void frmConfig_Load_1(object sender, EventArgs e)
        {
            try
            {
                System.IO.Stream xsdResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RackServerManager.Images.office.ico");
                this.pictureBoxIcon.Image = System.Drawing.Image.FromStream(xsdResourceStream);

                // Check the option selected by user on previous run
                if (Global.DTOption == Global.DataOption.Wmi)
                {
                    rbCPUCurrent.Checked = true;
                    
                }
                else if (Global.DTOption == Global.DataOption.Scom)
                {
                    txtBoxSCOMRoot.Text = Global.ServerName;
                    rbCPUDuration.Checked = true;
                 }

                if (Global.WindowsAuthentication == true)
                {
                    rbWindows.Checked = true;
                }
                else if (Global.UserCredentials == true)
                {
                    rbUsername.Checked = true;
                    txtBoxUsername.Text = Global.UserName;
                    txtBoxPassword.Text = Global.Password;
                    if (String.IsNullOrEmpty(Global.Password) ||
                            String.IsNullOrEmpty(Global.UserName))
                    {
                        tbCtrlConfig.SelectedIndex = 1;
                    }
                }

                cpuThresholdUpDwn.Value = Global.CpuUsageThreshold;
                maxServersUpDwn.Value = Global.MaxServerConsolidate;

            }
            catch (RackException ex)
            {

                // To catch and display exceptions from sub functions
                RackException.HandleExceptions(Global.GetResourceString("Exception_MsgBox_Caption"),
                            Global.GetResourceString("Exception_UsrMsg"), ex.InnerException);
            }
            catch (Exception ex)
            {
                // To catch exceptions from current functions
                RackException.HandleExceptions(Global.GetResourceString("Exception_MsgBox_Caption"),
                            Global.GetResourceString("Exception_UsrMsg"), ex);
            }
        }

        #endregion

        #region Methods

        ///// <summary>
        ///// Get registry key of the remote machine
        ///// </summary>
        ///// <param name="serverName"></param>
        ///// <param name="key"></param>
        ///// <returns></returns>
        //private static bool GetRemoteRegistry(string serverName, string key, out RegistryKey regKey)
        //{
        //    try
        //    {
        //        regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName).OpenSubKey(key);
        //        return true;
        //    }
        //    catch (Exception)
        //    {
        //        regKey = null;
        //        return false;
        //    }
        //}

        /// <summary>
        /// Check database name and access right on the database
        /// </summary>
        /// <returns></returns>
        //private static void CheckConnection(out string errorMsg)
        //{
        //    DBManager objDbManager = null;
        //    //DBManager objDbReportManager = null;

        //    try
        //    {
        //        // Get connection string for operations manager database
        //        String strConnection = Global.GetOpsDBConnString();


        //        // Get connection string for operations manager reporting database
        //        //String strConnectionReporting = Global.GetReportingDBConnString();

                
        //        try
        //        {
        //            // Get DB manager object for reporting management server
        //           // objDbReportManager = new DBManager(strConnectionReporting);
        //            // Get DB manager object for root management server
        //            objDbManager = new DBManager(strConnection);

        //        }
        //        catch (SqlException ex)
        //        {
        //            Global.ScomReportingServerAuthentication = false;
        //            throw new RackException(ex.Message);
        //        }

        //        // Create SP RSV_GetServerDetails
        //        DBManager.CreateStoredProc(objDbManager, Assembly.LoadFile(Global.AppPath() +
        //            "UtilityManager.dll").GetManifestResourceStream("UtilityManager.SQLScripts.RSV_GetServerDetails.sql"));

        //        // Create SP RSV_GetCPUUsage
        //        //DBManager.CreateStoredProc(objDbReportManager, Assembly.LoadFile(Global.AppPath() +
        //         //   "UtilityManager.dll").GetManifestResourceStream("UtilityManager.SQLScripts.RSV_GetServerUsage.sql"));

        //        errorMsg = string.Empty;
        //    }
        //    catch (RackException ex)
        //    {
        //        throw new RackException(ex.Message);
        //    }
        //    catch (Exception ex)
        //    {
        //        errorMsg = ex.Message;
        //    }
        //    finally
        //    {
        //        // Close connection if open
        //        if (objDbManager != null)
        //        {
        //            objDbManager.CloseConnection();
        //        }
        //        //if (objDbReportManager != null)
        //        //{
        //        //    objDbReportManager.CloseConnection();
        //        //}
        //    }
        //}
        #endregion

        private void tbPageData_Click(object sender, EventArgs e)
        {

        }
        
    }
}